<template>
    <div>
        <vue-json-editor style="height:300px" v-model="jsonData" :showBtns="false" :codes='["code"]' :mode="'code'"
            @json-change="onJsonChange" @json-save="onJsonSave" @has-error="onError">
        </vue-json-editor>
    </div>
</template>

<style lang="scss">
.jsoneditor-vue {
    height: 100%;
}

.jsoneditor-contextmenu {
    margin-top: 7px;
    margin-left: 10px;
}

.jsoneditor-menu {
    li {
        padding-left: 0px;
    }
}

.jsoneditor-modes:nth-child(1) {
    display: none;
}
</style>

<script>
import { DeepCopy } from '@/utils/Utils'
import vueJsonEditor from 'vue-json-editor'

export default {
    name: "VueJsonEditor",
    // 注册组件
    components: { vueJsonEditor },
    props: {
        json: {
            type: String,
            default: () => {
                return "{}"
            }
        }
    },
    data() {
        return {
            hasJsonFlag: true,
            jsonData: DeepCopy(JSON.parse(this.json)),
        }
    },
    mounted: function () {
        this.$nextTick(() => {
            this.createButton("Check", this.checkJson)
            this.createButton("Reset", this.resetJson)
        })
    },
    watch: {
        json(newJson, oldJson) {
            this.jsonData = DeepCopy(JSON.parse(newJson))
        }
    },
    methods: {
        onJsonChange(value) {
            console.log('更改value:', value);
            // 实时保存
            this.onJsonSave(value)
        },
        onJsonSave(value) {
            console.log('保存value:', JSON.stringify(value));
            this.jsonData = value
            this.hasJsonFlag = true
        },
        onError(value) {
            console.log("json错误了value:", value);
            this.hasJsonFlag = false
        },
        createButton(btnName, clickFn) {
            const button = document.createElement('button');
            button.textContent = btnName;
            button.setAttribute('type', 'button');
            button.classList.add('jsoneditor-modes');
            button.addEventListener('click', clickFn);
            const element = document.getElementsByClassName('jsoneditor-modes')[0];
            element.appendChild(button);
        },

        // 检查json
        checkJson() {
            if (this.hasJsonFlag == false) {
                this.$message.error("json验证失败")
                return false
            } else {
                this.$message.success("json验证成功")
                return true
            }
        },
        resetJson() {
            this.jsonData = DeepCopy(JSON.parse(this.json))
        },
    }
}
</script>

<style></style>